package com.js.rtu.mvp.present;


import android.util.Log;

import com.js.rtu.RTUApplication;
import com.js.rtu.base.BasePresenter;
import com.js.rtu.fragment.third.DebugReadBean;
import com.js.rtu.mvp.bean.Cmd02Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.CollectionGroupUtil;
import com.js.rtu.util.SPUtils;
import com.tencent.bugly.proguard.A;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 02点测数据解析
 * Created by wz on 2019/5/17.
 */
public class Cmd02Presenter implements BasePresenter<Cmd02Bean> {

    int index;
    @Override
    public CommonBean<Cmd02Bean> paseData(String msg) {
        Log.e("xxxx", msg);
        CommonBean<Cmd02Bean> bean = new CommonBean<>();
        Cmd02Bean cmd02Bean = new Cmd02Bean();
         index = 0;
        String[] data = msg.split(" ");
        if (getDataByIndex(data,0).equals("EE") && getDataByIndex(data,1).equals("EE")
                && getDataByIndex(data,data.length - 1).equals("FF")
                && getDataByIndex(data,data.length - 2).equals("FF")) {

            //帧头、CRC、帧尾
            bean.setStart(getDataByIndex(data,0) + getDataByIndex(data,1));
            bean.setCRC(getDataByIndex(data,data.length - 4) + getDataByIndex(data,data.length - 3));
            bean.setEnd(getDataByIndex(data,data.length - 1) + getDataByIndex(data,data.length - 2));
            index = 2;//2字节

            //address
            StringBuilder str_address = new StringBuilder();
            for (int i = 0; i < 8; i++) {
                str_address.append(getDataByIndex(data,index + i));
            }
            index += 8;//8字节
            String address = BleUtils.hexStr2Str(str_address.toString());
            bean.setAddress(address);


            //length固定长度2，hex
            int length = BleUtils.hToint(getDataByIndex(data,index+1) + getDataByIndex(data,index));
            index += 2;//2字节
            bean.setLength(length);


            //cmd固定长度1
            int cmd = Integer.parseInt(getDataByIndex(data,index));
            index += 1;//1字节
            bean.setCmd(cmd);


            //time固定长度6，hex

            String str_time = "20" +
                    BleUtils.hToint(getDataByIndex(data,index)) + "/" +
                    String.format(Locale.CHINA, "%02d",
                            BleUtils.hToint(getDataByIndex(data,index+1))) +
                    "/" +
                    String.format(Locale.CHINA, "%02d",
                            BleUtils.hToint(getDataByIndex(data,index+2))) +
                    " " +
                    String.format(Locale.CHINA, "%02d",
                            BleUtils.hToint(getDataByIndex(data,index+3))) +
                    ":" +
                    String.format(Locale.CHINA, "%02d",
                            BleUtils.hToint(getDataByIndex(data,index+4))) +
                    ":" +
                    String.format(Locale.CHINA, "%02d",
                            BleUtils.hToint(getDataByIndex(data,index+5)));
            index += 6;
            cmd02Bean.setTime(str_time);
            boolean isBreak = false;
            //这里开始就是data数据
            while (index < data.length - 1&& !isBreak) {
                //识别的字段
                String start = getDataByIndex(data,index++).toUpperCase();
                //这个字段后面数据长度
                int dataLength = BleUtils.hToint( getDataByIndex(data,index++));
                switch (start) {
                    case "0C":
                        List<String> OCList = new ArrayList<>();
                        for (int i = 0; i < dataLength; i++) {
                            //2字节一个整形数，低位在前
                            OCList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data,index+1) + getDataByIndex(data,index))));
                            index += 2;
                        }
                        cmd02Bean.setOCList(OCList);
                        break;

                    case "0F":
                        List<String> OFList = new ArrayList<>();
                        for (int i = 0; i < dataLength; i++) {
                            //4字节一个浮点数，低位在前，转换成byte再取对应位数
                            OFList.add(BleUtils.byte2Float(getDataByIndex(data,index+3) + getDataByIndex(data,index+2)
                                    + getDataByIndex(data,index+1) + getDataByIndex(data,index)));
                            index += 4;
                        }
                        cmd02Bean.setOFList(OFList);
                        break;

                    case "0A":
                        List<String> OAList = new ArrayList<>();
                        for (int i = 0; i < dataLength; i++) {
                            //2字节一个整形数，低位在前
                            OAList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data,index+1) + getDataByIndex(data,index))));
                            index += 2;
                        }
                        cmd02Bean.setOAList(OAList);
                        break;

                    case "0D":
                        List<String> ODList = new ArrayList<>();
                        //1byte8位，每位代表一个开关量，如03-->0000 0011 di0=1,di1=1;
                        //长度除8向上取整，即是byte的长度
                        float number = dataLength / 8.0f;
                        int count = (int) Math.ceil(number);
                        for (int i = 0; i < count; i++) {
                            //转二进制, 补齐8位
                            String di = BleUtils.toBinary(BleUtils.hToint(getDataByIndex(data,index)), 8);
                            index++;//下一组8bit
                            for (int j = 0; j < di.length(); j++) {
                                if (dataLength != 0) {
                                    ODList.add(di.substring(di.length() - 1 - j, di.length() - j));
                                    dataLength--;//剩余读取开关量数减一
                                }
                            }
                        }
                        cmd02Bean.setODList(ODList);
                        break;

                    case "0B":
                        //每通道长整型数据 4 字节整型，
                        if (dataLength != 0) {
                            if (getDataByIndex(data,index).toUpperCase().equals("0E")) {
                                index += 4;
                            } else {
                                List<String> OBList = new ArrayList<>();
                                for (int i = 0; i < dataLength; i++) {
                                    OBList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data,index+3) + getDataByIndex(data,index+2)
                                            + getDataByIndex(data,index+1) + getDataByIndex(data,index))));
                                    index += 4;
                                }
                                cmd02Bean.setOBList(OBList);
                            }
                        }

                        break;
                    case "0E":
//                        List<String> OEList = new ArrayList<>();
////                        for (int i = 0; i < dataLength; i++) {
//                            OEList.add(String.valueOf(BleUtils.hToint(getDataByIndex(data,index+1) + getDataByIndex(data,index))));
//                            index += 2;
////                        }
//                        cmd02Bean.setOEList(OEList);
                        isBreak = true;
                        break;
                    case "FF":

                        break;

                }
            }
        }
        bean.setData(cmd02Bean);
        return bean;

    }

    private String getDataByIndex(String[] data, int index) {
        StringBuilder stringBuilder = new StringBuilder();
        if (index < data.length ) {
            stringBuilder.append(data[index]).append(" ");
        } else {
            this.index = data.length - 1;
        }
        if (stringBuilder.length()>0) {
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }else {
            return stringBuilder.toString();
        }
    }

    public void setInfo(CommonBean<Cmd02Bean> bean) {
        String lineStart = "--------------------------↓--------------------------------\n";
        String lineEnd =   "--------------------------↑--------------------------------\n";
        Cmd02Bean data = bean.getData();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(lineStart);
        stringBuilder
                .append(String.format("实时%02d:   ", bean.getCmd()))
                .append(String.format("%s,   ", data.getTime()))
                .append(String.format("%s;\n", bean.getAddress()));
        float ai1 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai1", 600f);
        float ai2 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai2", 600f);
        float ai3 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai3", 600f);
        float ai4 = (float) SPUtils.get(RTUApplication.getAppContext(), "ai4", 600f);
        float power = (float) SPUtils.get(RTUApplication.getAppContext(), "power", 3.7f);
        List<Float> aiList = new ArrayList<>();
        aiList.add(ai1);
        aiList.add(ai2);
        aiList.add(ai3);
        aiList.add(ai4);

        List<String> oaList = data.getOAList();
        if (oaList != null && oaList.size() != 0) {
//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>模拟量数据↓<<<<<<<<"));
//            List<String> oaListsss = new ArrayList<>();
//            oaListsss.add(oaList.get(0));
//            oaListsss.add(oaList.get(oaList.size() - 1));
//            oaListsss.add(oaList.get(oaList.size() - 2));
//            for (int i = 1; i < oaList.size() - 2; i++) {
//                oaListsss.add(oaList.get(i));
//            }
//            oaList.clear();
//            oaList.addAll(oaListsss);
            //第一个CSQ,最后一个温度，倒数第二电压，其他为AI
            int aiNum = 0;
            Log.e("xxxxxxxx", oaList.toString());
            List<String> oaStr=new ArrayList<>();
            for (int i = 0; i < oaList.size(); i++) {

                float a = Float.parseFloat(oaList.get(i));
                if (i == 0) {
                    //csq
                    a = (a - 800) / 3200 * 255;//（信号强度值*3200）/255+800
                    if (a <= 0) {
                        a = 0;
                    }
                    if (a >= 255) {
                        a = 255;
                    }
                    stringBuilder.append(String.format(Locale.CHINA, "CSQ = %s (%.1f);  ", oaList.get(i), a));
                } else if (i == (oaList.size() - 2)) {
                    a = (a - 800) / 3200 * power;//AD：800-4000对应0-3.7
//                        p = (p - 800) / 3200 * 3.7f;//AD：800-4000对应0-3.7
                    if (a <= 0) {
                        a = 0;
                    }
                    if (a >= power) {
                        a = power;
                    }

                    stringBuilder.append(String.format(Locale.CHINA, "电池电压 = %s (%.1f);  ", oaList.get(i), a));
                } else if (i == (oaList.size() - 1)) {
                    a = (a - 800) / 3200 * 100;//AD：800-4000对应0-100度
                    if (a <= 0) {
                        a = 0;
                    }
                    if (a >= 100) {
                        a = 100;
                    }
                    stringBuilder.append(String.format(Locale.CHINA, "温度 = %s (%.1f);\n", oaList.get(i), a));
                } else {
                    //根据设定的ai值解析，没有就使用默认
                    if (aiNum >= aiList.size()) {
                        a = (a - 800) / 3200 * 600;//AD：800-4000对应0-100度
                        if (a <= 0) {
                            a = 0;
                        }
                        if (a >= 600) {
                            a = 600;
                        }
                    } else {
                        a = (a - 800) / 3200 * aiList.get(aiNum);//AD：800-4000对应0-100度
                        if (a <= 0) {
                            a = 0;
                        }
                        if (a >= aiList.get(aiNum)) {
                            a = aiList.get(aiNum);
                        }
                    }
//                    stringBuilder.append(String.format(Locale.CHINA, "AI[%s]=%s(%.1f)\n", aiNum, oaList.get(i), a));
                    aiNum++;
                    oaStr.add(String.format(Locale.CHINA, "AI[%s] = %s (%.1f); ", aiNum, oaList.get(i), a));
                }
            }
            if (oaStr.size()>=2) {
                List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(oaStr, 2);
                for (List<String> strings : groupList) {
                    for (String string : strings) {
                        stringBuilder.append(string);
                    }
                    stringBuilder.append("\n");
                }


            }else {
                for (String s : oaStr) {
                    stringBuilder.append(s);
                }
                stringBuilder.append("\n");
            }
        }

        List<String> oFList = data.getOFList();
        if (oFList != null && oFList.size() != 0) {

//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>浮点数数据<<<<<<<<"));
//            6个一组
            if (oFList.size()>=10){
          int  flNum= (int) SPUtils.get(RTUApplication.getAppContext(), "fl", 6);
                List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(oFList, flNum);
                for (int g = 0; g < groupList.size(); g++) {
                    stringBuilder
                            .append(String.format("Flow[%s] = %s ;\n  ", g,groupList.get(g).toString()));
                }
            }else {
                int num=0;
                for (int i = 0; i < oFList.size(); i++) {
                    stringBuilder
                            .append(String.format("FL[%s] = %s ;  ", i,oFList.get(i)));
                    num++;
                    if (num>=2) {
                        num=0;
                        stringBuilder.append("\n");
                    }
                }
            }

        }

        List<String> oDList = data.getODList();
        if (oDList != null && oDList.size() != 0) {
//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>开关量数据<<<<<<<<"));
            int num=0;
            for (int i = 0; i < oDList.size(); i++) {
                stringBuilder.append(String.format("DI[%s] = %s;   ", i, oDList.get(i)));
                num++;
                if (num>=2){
                    num=0;
                    stringBuilder.append("\n");
                }
            }

        }


        List<String> obList = data.getOBList();
        if (obList != null && obList.size() != 0) {
//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>长整型数据<<<<<<<<"));
            for (int i = 0; i < obList.size(); i++) {
                stringBuilder.append(String.format("长整型%s = %s\n", i, obList.get(i)));
            }

        }


        List<String> oeList = data.getOEList();
        if (oeList != null && oeList.size() != 0) {
//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>开关量连续运行时间数据<<<<<<<<"));
            for (int i = 0; i < oeList.size(); i++) {
                stringBuilder.append(String.format("连续运行时间%s = %s\n", i, oeList.get(i)));
            }

        }


        List<String> ocList = data.getOCList();
        if (ocList != null && ocList.size() != 0) {
//            stringBuilder
//                    .append(String.format("%s\n", ">>>>>>>>COD数据<<<<<<<<"));
            for (int i = 0; i < ocList.size(); i++) {
                stringBuilder.append(String.format("COD%s = %s\n", i, ocList.get(i)));
            }

        }
        stringBuilder.append(lineEnd);
        EventBus.getDefault().post(new DebugReadBean(stringBuilder.toString()));
        Log.e("xxxxxxxx",stringBuilder.toString());
    }

}





